package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
public class CacheClient {
    @Resource
    StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    // 1. 将任意一个对象序列化为JSON，并存储在String的Key中，并设置TTL过期时间
    public void set(String key, Object value, Long time, TimeUnit unit) {
        String s = JSONUtil.toJsonStr(value);
        stringRedisTemplate.opsForValue().set(key, s, time, unit);
    }

    // 2. 将任意一个对象序列化为JSON，并存储在String的Key中，并设置逻辑过期时间
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        String s = JSONUtil.toJsonStr(redisData);
        stringRedisTemplate.opsForValue().set(key, s);
    }
    // 3. 根据指定的key查询缓存，并反序列化为指定类型，利用缓存空值，解决缓存击穿的问题
    public <R, ID> R getWithPassThrough(String keyPrefix, ID id, Class<R> type,
                                        Function<ID, R> callBack, Long time, TimeUnit unit) {
        // 1. 拼接key
        String key = keyPrefix + id;
        // 2. 获取数据
        String data = stringRedisTemplate.opsForValue().get(key);
        // 3. 判断是否存在
        if(StrUtil.isNotBlank(data)) {
            // 4. 存在直接 返回
            return JSONUtil.toBean(data, type);
        }
        // 4. 如果命中空值返回null
        if("".equals(data)) {
            return null;
        }
        R r = callBack.apply(id);
        // 5. 不存在缓存空值
        if(r == null) {
            stringRedisTemplate.opsForValue().set(key, "", time, unit);
            return null;
        }
        // 6. 存在返回r
        this.set(key, r, time, unit);
        return r;
    }

    // 4. 查询，但是使用逻辑过期解决缓存击穿，key一定存在
    public <R, ID> R getWithLogicalEX(String keyPrefix, ID id, Class<R> type,
                                        Function<ID, R> callBack, Long time, TimeUnit unit) {
        System.out.println("getWithLogicalEX");
        // 1. 拼接key
        String key = keyPrefix + id;
        // 2. 获取数据
        String data = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isBlank(data)) {
            return null;
        }
        RedisData redisData = JSONUtil.toBean(data, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        JSONObject jsonData = (JSONObject) redisData.getData();
        R Rdata = JSONUtil.toBean(jsonData, type);
        // 3. 判断是否过期 如果当前时间在过期时间前面，就是没有过期
        if(LocalDateTime.now().isBefore(expireTime)) {
            System.out.println("go cache");
            return Rdata;
        }
        // 4. 否则重建缓存
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey, RedisConstants.LOCK_SHOP_TTL);
        // 4.1 如果拿到锁，进行重建，否则直接返回旧数据
        if(isLock) {
            try {
                CACHE_REBUILD_EXECUTOR.submit(() -> {
                    R result = callBack.apply(id);
                    System.out.println("reBuild");
                    this.setWithLogicalExpire(key, result, time, unit);
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                unLock(lockKey);
            }
        }
        return Rdata;
    }
    private boolean tryLock(String key, Long lockTTL) {
        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", lockTTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(result);
    }
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }
}
